/*
 * @Author: byron
 * @Date: 2022-01-25 17:42:34
 * @LastEditTime: 2022-02-08 16:42:00
 */

/**
 * 平滑滚动函数
 * @param {目标元素高度} targetHeight
 * @param {步长} step
 */
export function smoothSlide(targetHeight, step = 6) {
    let timer = setInterval(() => {
        let start =
            document.documentElement.scrollTop || document.body.scrollTop
        // 滚动条需要移动的距离
        let distance = targetHeight - start
        let ch = Math.floor(document.documentElement.clientHeight)
        let st = Math.floor(document.documentElement.scrollTop)
        let sh = Math.floor(document.documentElement.scrollHeight)
        let ispeed = Math.floor(distance / step)
        // 到达位置或者滚动条已经到底
        if (ispeed == 0 || ch + st == sh) {
            clearInterval(timer)
        }
        document.documentElement.scrollTop = document.body.scrollTop =
            start + ispeed
    }, 16)
}

// 防抖函数的编写
export const throttle = (fn, delay = 0) => {
    let flag = true
    return () => {
        if (!flag) return
        flag = false
        setTimeout(() => {
            fn()
            flag = true
        }, delay)
    }
}